package com.newtouch.bxzs.database.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.model.User;
import com.newtouch.bxzs.common.base.model.UserPositionMap;
import com.newtouch.bxzs.common.base.util.Assert;
import com.newtouch.bxzs.common.base.util.MD5Util;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;
import com.newtouch.bxzs.database.constant.DataBaseConstant;
import com.newtouch.bxzs.database.mapper.OrganizationMapper;
import com.newtouch.bxzs.database.mapper.UserMapper;
import com.newtouch.bxzs.database.mapper.UserPositionMapMapper;
import com.newtouch.bxzs.database.model.bo.*;
import com.newtouch.bxzs.database.model.vo.*;
import com.newtouch.bxzs.database.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 用户Service实现类:
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/1/6 17:34</td>
 * <td>tianshangzhu</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author tianshangzhu
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserPositionMapMapper userPositionMapMapper;

    @Resource
    private OrganizationMapper organizationMapper;

    /**
     * 查询后台用户列表信息
     *
     * @param getPcUserListVO 参数
     * @return IPage<PcUserListBO>
     */
    @Override
    public IPage<PcUserListBO> getUserList4Pc(GetPcUserListVO getPcUserListVO) {
        // 封装分页参数
        Page<PcUserListBO> page = new Page<>();
        page.setSize(getPcUserListVO.getPageSize());
        page.setCurrent(getPcUserListVO.getCurrentPage());
        // 查询
        return userMapper.getUserList4Pc(page, getPcUserListVO.getKeyWord());
    }

    /**
     * 查看后台用户详情信息
     *
     * @param userId 用户id
     * @return PcUseDetailBO
     */
    @Override
    public PcUseDetailBO getUserDetail4Pc(String userId) {
        PcUseDetailBO userDetail4Pc = userMapper.getUserDetail4Pc(userId);
        // 根据用户角色 角色岗位查询用户的岗位
        List<SimplePositionBO> positions = userPositionMapMapper.selectUserPositionName(userId, DataBaseConstant.TERMINAL_TYPE_PC);
        List<String> positionIdList = new ArrayList<>();
        List<String> positionNameList = new ArrayList<>();
        if (positions != null && !positions.isEmpty()) {
            for (SimplePositionBO position : positions) {
                positionIdList.add(position.getPositionId());
                positionNameList.add(position.getPositionName());
            }
        }
        userDetail4Pc.setPositionNameList(positionNameList);
        userDetail4Pc.setPositionIdList(positionIdList);
        return userDetail4Pc;
    }

    /**
     * 添加/修改后台用户信息
     *
     * @param updatePcUserVO 参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePcUser(UpdatePcUserVO updatePcUserVO) {
        Assert.notEmpty(updatePcUserVO.getPositionIds(), "【岗位】为必录项，请填写");
        // 维护用户表中的用户名，是否后台管理用户，修改人，修改时间
        User user = new User();
        BeanUtils.copyProperties(updatePcUserVO, user);
        user.setUpdateTime(new Date());
        user.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        user.setPlatformManagementUserFlag(true);
        // 新增后台用户，后台用户状态默认为禁用
        if(updatePcUserVO.getIsAdd().equals(DataBaseConstant.OPERATION_TYPE_1)){
            user.setEnablePlatformManagementUserFlag(false);
        }
        userMapper.updateById(user);

        // 维护用户岗位中间表（先删除，后添加）
        userPositionMapMapper.deleteOldPcPositionByUserId(updatePcUserVO.getUserId());
        // 岗位id不为空则插入
        if(updatePcUserVO.getPositionIds() != null && !updatePcUserVO.getPositionIds().isEmpty()){
            insertIntoUserPositionMap(updatePcUserVO.getUserId(), updatePcUserVO.getPositionIds());
        }
    }

    /**
     * 用户岗位角色中间表数据插入
     *
     * @param userId      用户id
     * @param positionIds 岗位id集合
     */
    public void insertIntoUserPositionMap(String userId, List<String> positionIds) {
        for (String positionId : positionIds) {
            UserPositionMap userPositionMap = new UserPositionMap();
            Date date = new Date();
            userPositionMap.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            userPositionMap.setCreateTime(date);
            userPositionMap.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            userPositionMap.setUpdateTime(date);
            userPositionMap.setUserId(userId);
            userPositionMap.setPositionId(positionId);
            userPositionMapMapper.insert(userPositionMap);
        }
    }

    /**
     * 删除后台用户
     *
     * @param userIdList 用户id
     */
    @Override
    public void deletePcUserByUserId(List<String> userIdList) {
        // 删除用户前需要判断传入的用户是否有使用中的用户
        int count = userMapper.checkPcUserIsEnable(userIdList);
        if (count < userIdList.size()) {
            // 如果统计出来的比传入的人数少，说明选中的用户中有启用状态的
            throw new BaseException(BaseErrorEnum.ENABLE_USE);
        }
        // 修改ASSISTANT_USER表的状态
        userMapper.deletePcUserByUserId(userIdList);
        // 删除用户的后台岗位 用户岗位表的数据删除
        userPositionMapMapper.deleteByUserIdBatch(userIdList);
    }


    /**
     * 重置后台用户登录密码
     *
     * @param userId 用户id
     */
    @Override
    public void resetPassword4Pc(String userId) {
        // 将初始密码Md5加密后存入数据库
        String md5ofStr = MD5Util.getMD5ofStr(MD5Util.getMD5ofStr(DataBaseConstant.INIT_PASSWORD));
        userMapper.resetPassword4Pc(userId, md5ofStr);
    }

    /**
     * 后台用户添加/用户选择接口
     *
     * @param getAppUserListVO 参数
     * @return IPage<AppUserList4AddPcUserBO>
     */
    @Override
    public IPage<AppUserList4AddPcUserBO> getAppUserList4AddPcUser(GetAppUserListVO getAppUserListVO) {
        Page<AppUserList4AddPcUserBO> page = new Page<>(getAppUserListVO.getCurrentPage(), getAppUserListVO.getPageSize());
        return userMapper.getAppUserList4AddPcUser(page, getAppUserListVO.getKeyWord());
    }


    /**
     * 获取登录用户所属机构及以下机构的App用户列表
     *
     * @param getAppUserListVO 参数
     * @return IPage<AppUserListBO>
     */
    @Override
    public IPage<AppUserListBO> getUserList4App(GetAppUserListVO getAppUserListVO) {
        String organizationCode = getAppUserListVO.getOrganizationCode();
        // 如果前端传入organizationCode为空，取当前登录用户的organizationCode
        if ("".equals(organizationCode) || organizationCode == null) {
            organizationCode = Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserOrganizationCode();
        }

        // 根据用户机构code查出用户的所有子级机构code
        String childOrganizationCodeStr = organizationMapper.selectChildOrganizationCodeStr(organizationCode);
        String[] childOrgCodeArr = childOrganizationCodeStr.split(",");
        // 处理分页参数
        Page<AppUserListBO> page = new Page<>(getAppUserListVO.getCurrentPage(), getAppUserListVO.getPageSize());
        // 查询
        return userMapper.getUserList4App(page, childOrgCodeArr, getAppUserListVO.getKeyWord());
    }

    /**
     * 根据用户工号展示银行/保险用户详情信息
     *
     * @param userId 用户id
     * @return AppUserDetailBo
     */
    @Override
    public AppUserDetailBO getUserDetail4App(String userId) {
        PcUseDetailBO userDetail4Pc = userMapper.getUserDetail4Pc(userId);
        // 根据用户角色 角色岗位查询用户的岗位
        List<SimplePositionBO> positions = userPositionMapMapper.selectUserPositionName(userId, DataBaseConstant.TERMINAL_TYPE_APP);
        List<String> positionIdList = new ArrayList<>();
        List<String> positionNameList = new ArrayList<>();
        if (positions != null && !positions.isEmpty()) {
            for (SimplePositionBO position : positions) {
                positionIdList.add(position.getPositionId());
                positionNameList.add(position.getPositionName());
            }
        }
        userDetail4Pc.setPositionNameList(positionNameList);
        userDetail4Pc.setPositionIdList(positionIdList);
        AppUserDetailBO appUserDetailBO = new AppUserDetailBO();
        BeanUtils.copyProperties(userDetail4Pc,appUserDetailBO);
        return appUserDetailBO;
    }

    /**
     * 获取用户所有菜单
     *
     * @param getUserMenuListVO 参数
     * @return UserMenuListBO
     */
    @Override
    public UserMenuListBO getUserMenuList(GetUserMenuListVO getUserMenuListVO) {
        return userMapper.getUserMenuList(getUserMenuListVO);
    }

    /**
     * 启用/禁用后台用户
     *
     * @param updateStateVO 参数
     */
    @Override
    public void updatePcUserState(UpdateStateVO updateStateVO) {
        // 修改
        userMapper.modifyPlatformManagementUserState(updateStateVO.getServiceId(), updateStateVO.getEnableFlag());
    }

    /**
     * app端根据机构编码查询用户
     *
     * @param getAppUserVO 参数
     * @return 用户信息
     */
    @Override
    public List<AppSimpleUserBO> getAppSimpleUser(GetAppUserVO getAppUserVO) {
        Assert.notEmpty(getAppUserVO, "参数不能为空");
        Assert.notEmpty(getAppUserVO.getOrganizationCode(), "参数机构编码不能为空");

        return userMapper.getAppSimpleUser(getAppUserVO);
    }

    /**
     * 修改用户岗位
     *
     * @param updateUserPositionVO 参数
     */
    @Override
    public void updateUserPosition(UpdateUserPositionVO updateUserPositionVO) {
        String userId = updateUserPositionVO.getUserId();
        // 删除用户所属端的所有岗位,先查出用户岗位中间表的所有id
        List<String> userPositionIdList = userPositionMapMapper.selectByUserId(userId, updateUserPositionVO.getTerminalType());
        if(!userPositionIdList.isEmpty()){
            userPositionMapMapper.deleteBatchIds(userPositionIdList);
        }

        // 插入新的岗位
        List<String> positionsIdList = updateUserPositionVO.getPositionIds();
        List<UserPositionMap> list = new ArrayList<>();
        if (positionsIdList != null && !positionsIdList.isEmpty()) {
            for (String positionId : positionsIdList) {
                UserPositionMap userPositionMap = new UserPositionMap();
                userPositionMap.setUserId(userId);
                userPositionMap.setPositionId(positionId);
                userPositionMap.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
                userPositionMap.setCreateTime(new Date());
                list.add(userPositionMap);
            }
            // 批量插入
            userPositionMapMapper.saveBatch(list);
        }
    }
}

